<template>
  <section>
     <!-- 面包屑 -->
 <breadcrumbs></breadcrumbs>
    <div class="top-box">
      <div class="top-item"><img src="../../assets/images/leijikuaidichengben.png"
             alt=""
             class="top-icon">
        <div class="right-item-box">
          <p><span class="fontTop">{{topData.allNum/100}}</span><br>
            <span class="fontText">累计快递成本(元)</span>
          </p>
        </div>
      </div>
      <div class="top-item"><img src="../../assets/images/daijiesuankuaidichengben.png"
             alt=""
             class="top-icon">
        <div class="right-item-box">
          <p><span class="fontTop">{{topData.notPayNum/100}}</span><br>
            <span class="fontText">待结算快递成本(元)</span>
          </p>
        </div>
      </div>

    </div>
    <!-- 查询条件 -->
    <el-form ref="searchForm"
             :model="searchForm"
             label-width="100px"
             inline
             class="demo-form-inline"
             size='small'
             style="border-bottom: 1px solid #f6f6f6;">
      <el-form-item label="请选择账期"
                    prop="name">
        <el-date-picker v-model="searchForm.date"
                        value-format="yyyy-MM"
                        type="month"
                        placeholder="选择账期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.state"
                   placeholder="请选择状态">
          <el-option label="待结算"
                     value="0"></el-option>
          <el-option label="已结算"
                     value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   @click="search">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <btns @exec="exec"
          class="marbt20px"></btns>
    <div>
      <p>总订单数，当前总计：&nbsp;&nbsp;<span>{{searchForm.totalCount}}</span>
        <!-- <el-button class="exports-btn"
                   @click="goExports"
                   type="primary">导出</el-button>
        <el-button class="exports-btn"
                   @click="goPay"
                   type="primary">结算</el-button> -->
      </p>
    </div>
    <div class="data-container scroll-table">
      <!-- 按钮列表 -->
      <el-table :data="tableData"
                border
                style="width: 100%"
                @selection-change="tableSelectionChange">
        <el-table-column type="selection"
                         width="40">
        </el-table-column>
        <el-table-column type="index"
                         label="序号"
                         width="50">
        </el-table-column>
        <el-table-column prop="years"
                         label="账单周期">
        </el-table-column>
        <el-table-column prop="orderCount"
                         label="已入库单数">
        </el-table-column>
        <el-table-column prop="allCount"
                         label="已入库总数">
        </el-table-column>
        <el-table-column prop="cost"
                         label="物流总成本">
        </el-table-column>
        <el-table-column prop="paytime"
                         label="财务姓名">
        </el-table-column>
        <el-table-column prop="paytime"
                         label="结算时间">
        </el-table-column>
        <el-table-column prop="payState"
                         label="结算状态">
          <template slot-scope="scope">
            <div v-if="scope.row.payState==1">已结算</div>
            <div v-if="scope.row.payState==0">待结算</div>
          </template>
        </el-table-column>
        <el-table-column prop="state"
                         label="操作">
          <template slot-scope="scope">
            <el-button @click="showDetails(scope.row)">查看明细</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="mgt-10 pd-0"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="searchForm.current"
                     :page-sizes="[10, 20, 30, 50]"
                     :page-size="searchForm.size"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="searchForm.totalCount">
      </el-pagination>
    </div>
    <!--新增修改界面-->
    <!-- 确认结算 -->
    <el-dialog
      title="确认结算"
      :visible.sync="dialogVisible1"
      width="800px"
      center
      :before-close="clearJieSuan"
    >
      <el-form>
        <el-form-item label="结算账期" prop="resource">
          <div>{{ zhangdan }}</div>
          <!-- <el-input v-model="addForm.resource"></el-input> -->
        </el-form-item>
        <el-form-item label="选择结算回收站" style="margin-bottom: 60px">
          <el-form-item>
            <el-transfer
              :titles="['请选择', '已选择']"
              filterable
              filter-placeholder="请输入按钮名称"
              :props="{ key: 'itemId', label: 'itemName' }"
              v-model="itemIds"
              @change="payCountFun"
              :data="backstopList"
            ></el-transfer>
          </el-form-item>
        </el-form-item>
        <el-form-item label="总结算金额" prop="title" label-width="130px">
          <el-input v-model="countCost" disabled='disabled'></el-input>
        </el-form-item>

        <el-form-item class="mgt-100">
          <center>
            <el-button type="primary" @click="submitForm()"
              >确认结算</el-button
            >
            <el-button @click="clearJieSuan">取消</el-button>
          </center>
        </el-form-item>
      </el-form>
    </el-dialog>
  </section>
</template>

<script>

import btns from '@/components/btns.vue'
import { format } from "../../utils/tool"
import ExportExcel from "../../utils/ExportExcel.js";
import breadcrumbs from "@/components/breadcrumbs.vue";
export default {
  components: {
    btns,
    ExportExcel,
    breadcrumbs,
  },
  data () {
    return {
      dialogVisible1:false,
       countCost:'',
      itemIds: [],
      zhangdan:[],
      backstopList:[],
      addForm: {},
      yearData: "",
      topData: {},
      btnForm: {},
      searchForm: {
        current: 1,
        size: 10,
        info: "",
        sid: "",
        totalCount: 0,
      },
      totalmoney: '',
      addORUpdateVisible: false,
      funTit: '',
      cityForm: {
        cityName: "",
        cityId: ''
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      rules: {
        "btnIcon": [],
        "btnName": [
          { required: true, message: '请输入城市名称', trigger: 'blur' }
        ],
        "btnCode": [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ],
        "sort": [
          { required: true, message: '排序', trigger: 'blur' }
        ]
      },
      tableData: [],
      tableSelection: []
    }
  },
  created () {
    // this.btnlist();
    // this.getYearData();
    this.getTableData(1, 10, this.searchForm.info, this.searchForm.sid);
    this.getColList();
  },
  methods: {
    jiesuan() {
      if (this.tableSelection.length != 1) {
        return this.$message.error("请选中一行数据");
      }else if(this.tableSelection[0].payState==1){
        return this.$message.error("账单已结算");
      }
      this.zhangdan=this.tableSelection[0].years
      this.getHouseBackStopList();
      this.dialogVisible1 = true;
    },
    clearJieSuan(){
      this.dialogVisible1 = false;
      this.zhangdan='';
      this.itemIds=[];
      this.countCost='';
    },
    goPay() {
      this.dialogVisible1 = true;
    },
     //统计结算金额
    payCountFun(arr) {
      let cost=0
      this.backstopList.filter(b=>
        arr.findIndex(f=>f==b.itemId)!=-1
      ).forEach(f=>{
        cost+=f.allMoney
      })
      this.countCost=cost
    },
    //获取回收站列表
    getHouseBackStopList() {
      this.$api.finance
        .getHoBackStopListByMonth({ month:this.zhangdan, type: 2 })
        .then((d) => {
          if (d.code == 200) {
            this.backstopList = d.data;
          } else {
            this.$message.error(d.msg);
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
       submitForm(){
      if(this.itemIds.length==0){
        return this.$message.warning('请勾选结算回收站');
      }
      this.$api.finance
        .payCost({
          month: this.zhangdan,
          itemIds:this.itemIds.join(','),
          type:2
        })
        .then((d) => {
          if (d.code == 200) {
            this.clearJieSuan()
            this.$message.success('结算成功!');
            this.getTableData(1, 10, this.searchForm.info, this.searchForm.sid);
            this.getColList();
         } else {
            this.$message.error(d.msg);
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },



    export(){
       console.log("导出")
       this.$api.outorder
        .getcangkuOutOrderExcel({ 
          type:2

        })
        .then((d) => {
          let filename = "采购单物流成本明细表.xlsx";
          ExportExcel(d, filename); 
        })
        .catch((e) => {
          console.log(e);
        });

    },
    getColList () {
      this.$api.finance.getCostTotal({
        type: 2
      }).then((res => {
        if (res.code == 200) {
          this.topData = res.data;
        } else {
          this.$message.error(res.msg)
        }
      }))
    },
    goPay () { },
    goExports () {
      this.$api.finance.getUserOrderCostExcel().then((res => {
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "导出成功"
          })
        } else {
          this.$message.error(res.msg)
        }
      }))
    },
    showDetails (row) {
      console.log(row)
      this.$router.push({
        path: "/purchase/purchaseDetails",
        query: {
          billId: row.billId,
          ischeck: row.payState,
          allMoney: row.cost
        }
      })
    },
    handleSizeChange (v) {
      console.log(v)
      this.searchForm.size = v;
      this.getTableData(this.searchForm.current, v);
    },
    handleCurrentChange (v) {
      this.searchForm.current = v;
      this.getTableData(v, this.searchForm.size);
    },
    getTableData (curr, size, month, state) {
      this.$api.finance.getCostList({
        current: curr,
        size: size,
        month: month,
        type: 2,
        payState: state,
      }).then(res => {
        if (res.code == 200) {
          console.log(res.data);
          // let result = res.data.ipage.records;
          // let currsku = res.data.skuList;
          // result.forEach((item) => {
          //   currsku.forEach((op) => {
          //     if (item.backOrderId == op.backOrderId) {
          //       item.brandName = op.brandName;
          //       item.backSkuId = op.backSkuId;
          //       item.backCount = op.backCount;
          //       item.price = op.price;
          //       item.total = parseFloat(op.price) * parseFloat(op.backCount)
          //     }
          //   })
          // })
          // this.topData = res.data.allCount;
          this.tableData = res.data
          this.totalmoney = res.msg
          console.log(this.tableData, '1231231')
          this.searchForm.totalCount = res.totalCount;
          this.searchForm.size = res.pageSize
        }
      })
    },
    chageYearData () {
      this.$api.user.getAdminUserCount({
        year: this.yearData
      }).then(res => {
        if (res.code == 200) {
          this.topData = res.data
        }
      })
    },
    getYearData () {
      this.$api.user.getAdminUserCount().then(res => {
        if (res.code == 200) {
          this.topData = res.data;
        }
      })
    },
    handleReset () {
      this.$refs.searchForm.resetFields();
      this.getTableData(this.searchForm.current, this.searchForm.size);
    },
    search () {
      // if (this.searchForm.date != undefined && this.searchForm.date.length > 0) {
      this.getTableData(this.searchForm.current, this.searchForm.size, this.searchForm.date, this.searchForm.state)
      // } else {
      //   this.getTableData(this.searchForm.current, this.searchForm.size, "", "", this.searchForm.keywords, this.searchForm.info)
      // }
    },
    btnlist () {
      //获取接口
      this.$api.city.getList({}).then(d => {
        if (d.code == 200) {
          this.tableData = d.data;
        } else {
          this.$message.error(d.msg);
        }
      }).catch((e) => {
        console.log(e);
      })
    },
    tableSelectionChange (val) {
      this.tableSelection = val;
    },
    exec (fun) {
      if (this[fun]) {
        this.funTit = fun;
        this[fun]()
      } else {
        this.$message.error('方法未定义');
      }
    },
    add () {

      this.btnForm = {
        "btnIcon": "",
        "btnName": "",
        "btnCode": "",
        "sort": 0
      }
      this.addORUpdateVisible = true;
    },
    update () {
      if (this.tableSelection.length != 1) {
        this.$message.error('请选中一行数据');
        return
      }
      this.btnForm = this.tableSelection[0];
      this.addORUpdateVisible = true;
    },
    del () {
      if (this.tableSelection.length != 1) {
        this.$message.error('请选中一行数据');
        return
      }

    },
    refresh () {
      this.btnlist();
    },
    enable () {
      if (this.tableSelection.length != 1) {
        this.$message.error('请选中一行数据');
        return
      }
      var demo = this.tableSelection[0];
      if (demo.state == 1) {
        this.$message.error('该数据已启用');
        return
      }
      this.$confirm('此操作将启用该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.user.updateStatus({ userId: demo.wxUserId, status: 1 }).then(d => {
          if (d.code == 200) {
            this.getTableData(this.searchForm.current, this.searchForm.size, this.searchForm.info, this.searchForm.sid);
            this.$message.success('启用成功');
          } else {
            this.$message.error(d.msg);
          }
        }).catch((e) => {
          console.log(e);
        })
      });
    },
    disable () {
      if (this.tableSelection.length != 1) {
        this.$message.error('请选中一行数据');
        return
      }
      var demo = this.tableSelection[0];
      console.log(demo)
      if (demo.state == 2) {
        this.$message.error('该数据已禁用');
        return
      }
      this.$confirm('此操作将禁用该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.user.updateStatus({ userId: demo.wxUserId, status: 2 }).then(d => {
          if (d.code == 200) {
            this.getTableData(this.searchForm.current, this.searchForm.size, this.searchForm.info, this.searchForm.sid);
            this.$message.success('禁用成功');
          } else {
            this.$message.error(d.msg);
          }
        }).catch((e) => {
          console.log(e);
        })
      });
    },
    submit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.tableData.findIndex(c => c.btnCode == this.btnForm.btnCode) >= 0) {
            this.$message.error('code不能重复');
            return
          }
          if (this.funTit == 'add') {
            this.$api.system.btnadd(this.btnForm).then(d => {
              if (d.code == 200) {
                this.addORUpdateVisible = false;
                this.$refs.btnForm.resetFields();
                this.btnlist();
              } else {
                this.$message.error(d.msg);
              }
            }).catch((e) => {
              console.log(e);
            })
          } else {
            this.$api.system.btnupdate(this.btnForm).then(d => {
              if (d.code == 200) {
                this.addORUpdateVisible = false;
                this.$refs.btnForm.resetFields();
                this.btnlist();
              } else {
                this.$message.error(d.msg);
              }
            }).catch((e) => {
              console.log(e);
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
}

</script>
<style lang="less" scoped>
.exports-btn {
  margin-left: 20px;
}
.title-style {
  font-size: 25px;
}
.marbt20px {
  margin-bottom: 20px;
}
.fontText {
  font-size: 20px;
}
.fontTop {
  font-size: 40px;
}
.top-box {
  width: 100%;
  display: flex;
  margin-right: 30px;
  align-items: center;
  margin-bottom: 40px;
}
.top-item {
  margin-right: 30px;
  border: 1px gray solid;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 20%;
  padding: 20px;
  .top-icon {
    width: 35%;
    height: 35%;
   
  }
  .right-item-box {
    text-align: center;
    margin-left: 20px;
  }
}
</style>